import 'package:flutter/cupertino.dart';
import 'package:lib_core/lib_core.dart';

/// Author: Shper
/// Created: 2023-08-10
mixin GTFlutterLifecycleObserver {

  static void addObserver(GTFlutterLifecycleObserver observer) => GTFlutterLifecycleBinding.instance._observers.add(observer);

  static bool removeObserver(GTFlutterLifecycleObserver observer) => GTFlutterLifecycleBinding.instance._observers.remove(observer);

  void onLifecycleResumed() {
    GTLogger.debug('$runtimeType onLifecycleResumed');
  }

  void onLifecycleInactive() {
    GTLogger.debug('$runtimeType onLifecycleInactive');
  }

  void onLifecyclePaused() {
    GTLogger.debug('$runtimeType onLifecyclePaused');
  }

  void onLifecycleDetached() {
    GTLogger.debug('$runtimeType onLifecycleDetached');
  }
}

class GTFlutterLifecycleBinding {

  /// 单例
  static final GTFlutterLifecycleBinding _instance = GTFlutterLifecycleBinding._internal();

  static GTFlutterLifecycleBinding get instance => _instance;

  /// 私有的命名构造函数
  GTFlutterLifecycleBinding._internal();

  final List<GTFlutterLifecycleObserver> _observers = <GTFlutterLifecycleObserver>[];

  void handleAppLifecycleStateChanged(AppLifecycleState state) {
    GTLogger.debug('GTFlutterLifecycleBinding - state: ${state.name}');

    final observers = List.from(_observers);
    switch (state) {
      case AppLifecycleState.resumed:
        for (var element in observers) {
          element.onLifecycleResumed();
        }
        break;
      case AppLifecycleState.inactive:
        for (var element in observers) {
          element.onLifecycleInactive();
        }
        break;
      case AppLifecycleState.paused:
        for (var element in observers) {
          element.onLifecyclePaused();
        }
        break;
      case AppLifecycleState.detached:
        for (var element in observers) {
          element.onLifecycleDetached();
        }
        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
    }
  }

}
